package com.fly.estore.framework.web.interceptor;

import com.fly.estore.framework.session.SessionManager;
import com.fly.estore.framework.util.CookieUtil;
import org.apache.http.HttpException;
import org.apache.http.HttpRequest;
import org.apache.http.protocol.HttpContext;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.servlet.handler.HandlerInterceptorAdapter;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;

/**
 * Created by Fly on 2016/3/25.
 */
public class AccountSessionInterceptor extends HandlerInterceptorAdapter {

    @Autowired
    SessionManager sessionManager;


    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
        //从cookie读取sessionId
        String sessionId = CookieUtil.readCookie(request, CookieUtil.ACCOUNT_COOKIE);
        //判断session是否存在
        if (null == sessionManager.getAccountSession(request, sessionId)){
            //session不存在，跳转到登录页面
            response.sendRedirect(request.getContextPath() + "/account/to-login");
            return false;
        }
        return true;
    }
}
